<template>
  <div id="app">
    <landing-page></landing-page>
    <el-dialog
        :title="dialogTitle"
        :visible.sync="dialogVisible"
        width="40%"
        :close-on-click-modal="closeOnClickModal"
        :close-on-press-escape="closeOnPressEscape"
        :show-close="showClose"
        center
    >
      <div style="width:100%;height:10vh;line-height:20vh;text-align:center">
        <el-progress
            status="success"
            :text-inside="true"
            :stroke-width="20"
            :percentage="percentage"
            :width="strokeWidth"
            :show-text="true"
        ></el-progress>
      </div>
      <div align="center">
        <el-button type=primary @click.prevent="upgrade" v-if="canUpgrade">更新</el-button>
        <el-button type=primary @click.prevent="upgradeLater"  v-if="canUpgradeLater">稍后</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import LandingPage from '@/components/LandingPage'
  import { ipcRenderer } from 'electron'
  export default {
    name: 'electrom-vue-update',
    components: {
      LandingPage
    },
    data () {
      return {
        dialogTitle: '正在更新新版本,请稍候...',
        dialogVisible: false,
        closeOnClickModal: false,
        closeOnPressEscape: false,
        showClose: false,
        canUpgrade: false,
        canUpgradeLater: false,
        percentage: 0,
        strokeWidth: 200
      }
    },
    methods: {
      upgrade () {
        ipcRenderer.send('upgradeVersion')
      },
      upgradeLater () {
        this.dialogVisible = false
      }
    },
    mounted () {
      ipcRenderer.on('message', (event, arg) => {
        if (arg.cmd === 'update-available') {
          this.dialogVisible = true
        } else if (arg.cmd === 'update-downloaded') {
          this.percentage = 100.0
          this.dialogVisible = '更新完成'
          this.canUpgrade = true
          this.canUpgradeLater = true
        } else if (arg.cmd === 'download-progress') {
          this.percentage = Math.round(parseFloat(arg.message.percent))
        } else if (arg.cmd === 'error') {
          this.dialogVisible = true
          this.canUpgradeLater = true
          this.dialogTitle = '版本更新错误，请和管理员联系'
        }
      })
      ipcRenderer.send('checkForUpdate')
    }
  }
</script>

<style>
  /* CSS */
</style>
